package com.webflux.controller;

import com.webflux.domain.User;
import com.webflux.repository.UserRepository;
import com.webflux.util.CheckUtil;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import javax.validation.Valid;

/**
 * Created by wangzhanjin on 2018/5/31.
 */
@RestController
@RequestMapping("/user")
public class UserController {

    private final UserRepository repository;

    /**
     * 官方推荐采用构造方式，跟Spring耦合度低
     *
     * @param repository
     */
    public UserController(UserRepository repository) {
        this.repository = repository;
    }

    @GetMapping("/")
    public Flux<User> getAll() {
//        throw new RuntimeException("测试使用");
        return repository.findAll();
    }

    @GetMapping(value = "/stream/all", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<User> streamGetAll() {
        return repository.findAll();
    }

    /**
     * 新增数据
     *
     * @param user
     * @return
     */
    @PostMapping("/")
    public Mono<User> createUser(@Valid @RequestBody User user) {
        //spring data jpa里面，新增和修改都是save，有id是修改,id为空是新增
        //根据实际情况是否置空id
        user.setId(null);
        CheckUtil.checkName(user.getName());
        return repository.save(user);
    }

    @RequestMapping("/str")
    public String createUser(@RequestParam String str) {
        return str + "路过";
    }



    /**
     * 根据id删除用户
     * 存在的时候返回200，不存在返回404
     *
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    public Mono<ResponseEntity<Void>> deleteUser(@PathVariable("id") String id) {
        //deleteById返回是voidMono，也就是没有返回值，不能判断数据是否存在
        return repository.findById(id)
                //当你要操作数据，并返回一个Mono，这时候使用flatMap
                //如果不操作数据，只是转换数据，使用map
                .flatMap(user -> repository.delete(user).then(Mono.just(new ResponseEntity<Void>(HttpStatus.OK))))
                .defaultIfEmpty(new ResponseEntity<>(HttpStatus.NOT_FOUND));
    }

    /**
     * 更新数据
     * @param id
     * @param user
     * @return
     */
    @PutMapping("/{id}")
    public Mono<ResponseEntity<User>> updateUser(@PathVariable("id") String id,
                                                 @Valid @RequestBody User user) {
        CheckUtil.checkName(user.getName());
        return this.repository.findById(id)
                //flatMap操作数据
                .flatMap(u -> {
                    u.setAge(user.getAge());
                    u.setName(user.getName());
                    //save方法后返回mono
                    return repository.save(u);
                })
                //转换数据
                .map(u -> new ResponseEntity<User>(u,HttpStatus.OK))
                .defaultIfEmpty(new ResponseEntity<>(HttpStatus.NOT_FOUND));
    }


    @GetMapping("/{id}")
    public Mono<ResponseEntity<User>> findUserById(@PathVariable("id") String id) {
        return this.repository.findById(id)
                //转换数据
                .map(u -> new ResponseEntity<User>(u,HttpStatus.OK))
                .defaultIfEmpty(new ResponseEntity<>(HttpStatus.NOT_FOUND));
    }


    /**
     * 根据年龄查询用户
     * @param start
     * @param end
     * @return
     */
    @GetMapping("/age/{start}/{end}")
    public Flux<User> findByAge(@PathVariable("start") int start, @PathVariable("end") int end) {
        return repository.findByAgeBetween(start, end);
    }


    @GetMapping(value = "/stream/age/{start}/{end}", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<User> streamFindByAge(@PathVariable("start") int start, @PathVariable("end") int end) {
        return repository.findByAgeBetween(start, end);
    }

    /**
     * 得到20~29的用户
     * @return
     */
    @GetMapping("/old")
    public Flux<User> oldUser() {
        return repository.oldUser();
    }


    @GetMapping(value = "/stream/old}", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<User> streamOldUser() {
        return repository.oldUser();
    }

}















